package se.id.vrapp;

import java.util.Locale;
import java.util.Random;

import android.app.Activity;
import android.content.Context;
import android.content.pm.ActivityInfo;
import android.graphics.Color;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.media.MediaPlayer;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.PowerManager;
import android.speech.tts.TextToSpeech;
import android.speech.tts.TextToSpeech.OnInitListener;
import android.util.Log;
import android.widget.SeekBar;
import android.widget.SeekBar.OnSeekBarChangeListener;
import android.widget.TextView;

public class MainActivity extends Activity implements SensorEventListener,
		OnInitListener {
	private SensorManager mSensorManager;
	private Sensor mLinearAccelerometer;

	private TextView title, tv, tv1, tv2, sensTitle, number;
	private SeekBar sensitivityB;

	private TextToSpeech speech;

	private int counter, index, sensitivity;
	private long cooldown, curTime;
	private float[] recent;
	private float threshold, avg;

	private Random random;
	private String[] speechLines = { "Go faster you fat bastard!",
			"I felt that", "Ouch, stop fucking hitting me!",
			"Oh yeah, smack me hard", "Damn, that hurt!",
			"Hit me, see if I care", "Well, fuck you too!",
			"That's not very nice!", "What the...",
			"What do you want from me?", "Getting real tired of your shit!",
			"What is your major malfunction?", "Hooray for boobies!" };

	private MediaPlayer mp;

	private PowerManager.WakeLock mWakeLock;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);

		mSensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
		mLinearAccelerometer = mSensorManager
				.getDefaultSensor(Sensor.TYPE_LINEAR_ACCELERATION);

		// Connecting views
		title = (TextView) findViewById(R.id.name);
		sensTitle = (TextView) findViewById(R.id.sensTitle);
		sensitivityB = (SeekBar) findViewById(R.id.sensitivity);
		tv = (TextView) findViewById(R.id.xval);
		tv1 = (TextView) findViewById(R.id.yval);
		tv2 = (TextView) findViewById(R.id.zval);
		number = (TextView) findViewById(R.id.number);

		// Initialization
		title.setText("Strike detector");
		sensTitle.setText("Sensitivity");
		number.setText("# strikes");

		random = new Random();

		threshold = 0;
		counter = 0;
		cooldown = 0;
		avg = 0;
		recent = new float[10];
		for (int i = 0; i < recent.length; i++) {
			recent[i] = 5;
		}
		index = 0;
		mp = MediaPlayer.create(getBaseContext(), R.raw.woohoo);
		sensitivity = 5;
		curTime = System.currentTimeMillis();

		speech = new TextToSpeech(this, this);

		sensitivityB.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {
			public void onProgressChanged(SeekBar seekBar, int progress,
					boolean fromUser) {
				sensitivity = progress;
			}

			public void onStartTrackingTouch(SeekBar seekBar) {
			}

			public void onStopTrackingTouch(SeekBar seekBar) {
			}
		});

		PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
		mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "My Tag");
		mWakeLock.acquire();
	}

	@Override
	public final void onAccuracyChanged(Sensor sensor, int accuracy) {
		// Do something here if sensor accuracy changes.
	}

	@Override
	public final void onSensorChanged(SensorEvent event) {
		curTime = System.currentTimeMillis();
		if (event.sensor.getType() == Sensor.TYPE_LINEAR_ACCELERATION) {
			avg = 0;
			for (int i = 0; i < recent.length; i++) {
				avg += recent[i];
			}
			avg = avg / recent.length;
			float x = Math.abs(event.values[0]);
			float y = Math.abs(event.values[1]);
			float z = Math.abs(event.values[2]) * 1.1f;
			if (curTime > cooldown) {
				tv1.setTextColor(Color.GREEN);
				threshold = (avg + 8 - sensitivity) * 3.0f;
				if ((x + y + z) > threshold && (x + y + z) > 2.5f) {
					strike();
				} else {
					recent[index] = x + y + z;
					if (index >= recent.length - 1)
						index = 0;
					else
						index++;
				}
			}
			tv.setText("" + sensitivity);
			tv1.setText("Accelerometer readings:\nX: "
					+ String.format("%.2f", x) + "\nY:"
					+ String.format("%.2f", y) + "\nZ: "
					+ String.format("%.2f", z) + "\nAvg: "
					+ String.format("%.2f", avg));
			tv2.setText("" + counter);
		}
	}

	@Override
	protected void onResume() {
		super.onResume();
		mSensorManager.registerListener(this, mLinearAccelerometer,
				SensorManager.SENSOR_DELAY_GAME);
		setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
	}

	@Override
	protected void onPause() {
		super.onPause();
		// mSensorManager.unregisterListener(this);
	}

	protected void strike() {
		counter++;
		speak();
		// mp.start();
		cooldown = curTime + 1000;
		Log.e("Strike()", "A strike was registered!");
	}

	private void speak() {
		String text = speechLines[random.nextInt(speechLines.length)];
		speech.speak(text, TextToSpeech.QUEUE_FLUSH, null);
	}

	@Override
	public void onInit(int status) {
		if (status == TextToSpeech.SUCCESS) {

			int result = speech.setLanguage(Locale.US);

			if (result == TextToSpeech.LANG_MISSING_DATA
					|| result == TextToSpeech.LANG_NOT_SUPPORTED) {
				Log.e("TTS", "This Language is not supported");
			} else {
			}

		} else {
			Log.e("TTS", "Initilization Failed!");
		}
	}

	private class StrikeMenu extends AsyncTask<Void, Void, Void> {

		@Override
		protected Void doInBackground(Void... arg0) {
			// TODO Auto-generated method stub
			return null;
		}

	}
}
